import {
  Request,
  Response,
  Router,
} from 'express';

import { IPaper } from '@shared/types/paper';

import { Paper } from '../models/paper.model';
import { Question } from '../models/question.model';
import { EnumStatusCode } from '@shared/constant/enum';

export const paperRouter = Router();

// 获取试卷列表（支持分页和筛选）
paperRouter.get("/list", async (req: Request, res: Response) => {
  try {
    const {
      page = 1,
      pageSize = 20,
      status,
      creator,
      keyword
    } = req.query;

    const filter: any = {};
    if (status) filter.status = status;
    if (creator) filter.creator = creator;
    if (keyword) {
      filter.paper_name = { $regex: keyword, $options: 'i' };
    }

    const limit = parseInt(pageSize as string);
    const skip = (parseInt(page as string) - 1) * limit;

    const papers = await Paper.find(filter)
      .populate('creator', 'username')
      .populate('question_list', 'content type score difficulty')
      .skip(skip)
      .limit(limit)
      .sort({ create_time: -1 });

    const total = await Paper.countDocuments(filter);

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "success",
      data: {
        data: papers,
        total_records: total,
        page: parseInt(page as string),
        limit,
        total_page: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    console.error('获取试卷列表失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "获取试卷列表失败",
      data: null
    });
  }
});

// 获取试卷详情
paperRouter.get("/detail", async (req: Request, res: Response) => {
  try {
    const { id } = req.query;
    if (!id) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "试卷ID不能为空",
        data: null
      });
    }

    const paper = await Paper.findById(id)
      .populate('creator', 'username')
      .populate('question_list');

    if (!paper) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "试卷不存在",
        data: null
      });
    }

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "success",
      data: paper
    });
  } catch (error) {
    console.error('获取试卷详情失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "获取试卷详情失败",
      data: null
    });
  }
});

// 创建试卷
paperRouter.post("/create", async (req: Request, res: Response) => {
  try {
    const paperData: IPaper = req.body;
    
    // 验证必填字段
    if (!paperData.paper_name || !paperData.question_list || 
        !paperData.duration || paperData.question_list.length === 0) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "请填写完整的试卷信息，至少包含一道题目",
        data: null
      });
    }

    // 验证试题是否存在
    const questions = await Question.find({ 
      _id: { $in: paperData.question_list } 
    });
    
    if (questions.length !== paperData.question_list.length) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "试卷中包含不存在的试题",
        data: null
      });
    }

    // 检查试卷名称是否重复
    const existingPaper = await Paper.findOne({ 
      paper_name: paperData.paper_name 
    });
    if (existingPaper) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "试卷名称已存在",
        data: null
      });
    }

    // 从认证用户中获取创建者ID
    paperData.creator = req.user?.user_id;

    const paper = new Paper(paperData);
    const savedPaper = await paper.save();
    
    // 返回包含关联数据的完整试卷信息
    const paperWithDetails = await Paper.findById(savedPaper._id)
      .populate('creator', 'username')
      .populate('question_list', 'content type score difficulty');

    res.status(EnumStatusCode.CREATED).json({
      code: EnumStatusCode.CREATED,
      message: "试卷创建成功",
      data: paperWithDetails
    });
  } catch (error) {
    console.error('创建试卷失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "创建试卷失败",
      data: null
    });
  }
});

// 更新试卷
paperRouter.post("/update", async (req: Request, res: Response) => {
  try {
    const { id, ...updateData } = req.body;
    
    if (!id) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "试卷ID不能为空",
        data: null
      });
    }

    // 检查试卷是否存在
    const existingPaper = await Paper.findById(id);
    if (!existingPaper) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "试卷不存在",
        data: null
      });
    }

    // TODO: 检查试卷是否被活动引用，如果是则限制修改
    
    // 如果更新试题列表，验证试题是否存在
    if (updateData.question_list) {
      const questions = await Question.find({ 
        _id: { $in: updateData.question_list } 
      });
      
      if (questions.length !== updateData.question_list.length) {
        return res.status(EnumStatusCode.BAD_REQUEST).json({
          code: EnumStatusCode.BAD_REQUEST,
          message: "试卷中包含不存在的试题",
          data: null
        });
      }
    }

    // 如果更新试卷名称，检查是否重复
    if (updateData.paper_name && updateData.paper_name !== existingPaper.paper_name) {
      const duplicatePaper = await Paper.findOne({ 
        paper_name: updateData.paper_name,
        _id: { $ne: id }
      });
      if (duplicatePaper) {
        return res.status(EnumStatusCode.BAD_REQUEST).json({
          code: EnumStatusCode.BAD_REQUEST,
          message: "试卷名称已存在",
          data: null
        });
      }
    }

    const updatedPaper = await Paper.findByIdAndUpdate(
      id,
      updateData,
      { new: true }
    ).populate('creator', 'username')
     .populate('question_list', 'content type score difficulty');

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "试卷更新成功",
      data: updatedPaper
    });
  } catch (error) {
    console.error('更新试卷失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "更新试卷失败",
      data: null
    });
  }
});

// 删除试卷
paperRouter.post("/delete", async (req: Request, res: Response) => {
  try {
    const { id, ids } = req.body;
    
    // TODO: 检查试卷是否被活动引用
    
    if (ids && Array.isArray(ids)) {
      // 批量删除
      const result = await Paper.deleteMany({ _id: { $in: ids } });
      res.json({
        code: EnumStatusCode.SUCCESS,
        message: `成功删除 ${result.deletedCount} 份试卷`,
        data: { deletedCount: result.deletedCount }
      });
    } else if (id) {
      // 单个删除
      const result = await Paper.findByIdAndDelete(id);
      if (!result) {
        return res.status(EnumStatusCode.NOT_FOUND).json({
          code: EnumStatusCode.NOT_FOUND,
          message: "试卷不存在",
          data: null
        });
      }
      res.json({
        code: EnumStatusCode.SUCCESS,
        message: "试卷删除成功",
        data: null
      });
    } else {
      res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "请提供要删除的试卷ID",
        data: null
      });
    }
  } catch (error) {
    console.error('删除试卷失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "删除试卷失败",
      data: null
    });
  }
});

// 预览试卷
paperRouter.get("/preview", async (req: Request, res: Response) => {
  try {
    const { id } = req.query;
    if (!id) {
      return res.status(EnumStatusCode.BAD_REQUEST).json({
        code: EnumStatusCode.BAD_REQUEST,
        message: "试卷ID不能为空",
        data: null
      });
    }

    const paper = await Paper.findById(id)
      .populate('creator', 'username')
      .populate('question_list');

    if (!paper) {
      return res.status(EnumStatusCode.NOT_FOUND).json({
        code: EnumStatusCode.NOT_FOUND,
        message: "试卷不存在",
        data: null
      });
    }

    // 计算统计信息
    const questionStats = {
      total: paper.question_list.length,
      byType: {} as Record<string, number>,
      byDifficulty: {} as Record<string, number>
    };

    (paper.question_list as any[]).forEach(question => {
      // 按题型统计
      questionStats.byType[question.type] = 
        (questionStats.byType[question.type] || 0) + 1;
      
      // 按难度统计
      questionStats.byDifficulty[question.difficulty] = 
        (questionStats.byDifficulty[question.difficulty] || 0) + 1;
    });

    res.json({
      code: EnumStatusCode.SUCCESS,
      message: "success",
      data: {
        ...paper.toObject(),
        statistics: questionStats
      }
    });
  } catch (error) {
    console.error('预览试卷失败:', error);
    res.status(EnumStatusCode.INTERNAL_SERVER_ERROR).json({
      code: EnumStatusCode.INTERNAL_SERVER_ERROR,
      message: "预览试卷失败",
      data: null
    });
  }
});
